package org.tong;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class StudentDao {

    private final static Logger logger = LoggerFactory.getLogger(StudentDao.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public List<Student> queryAll() {
        return jdbcTemplate.query("select * from student", getRowMapper());
    }

    @Cacheable(value = "student", key = "#p0")
    public Student queryById(Integer id) {
        logger.info("queryById {}", id);
        return jdbcTemplate.queryForObject("select * from student where id=?", getRowMapper(), id);
    }

    public int insert(Student student) {
        logger.info("insert %s", student.toString());
        return jdbcTemplate.update("insert into student (id, name)values(?, ?)", student.getId(), student.getName());
    }

    @CacheEvict(value = "student", key = "#p0")
    public int delete(Integer id) {
        logger.info("delete by id %d", id);
        return jdbcTemplate.update("delete from student where id=?", id);
    }

    private RowMapper<Student> getRowMapper() {
        return (rs, rowNum) -> {
            Student student = new Student();
            student.setId(rs.getInt(1));
            student.setName(rs.getString(2));
            return student;
        };
    }
}
